/**
 * 一些公共方法
 * Created by dongchen on 16/5/13.
 */
var _ = require('lodash');
var moment = require('moment');
var co = require('co');
var httpResult = require('./httpResult');

/**
 * 构建get请求的url
 * @param url
 * @param params
 * @returns {*}
 */
function buildUrlwithParams(url, params) {
    if (params && !_.isEmpty(params)) {
        url += '?';
        var pairs = [];
        for (var key in params) {
            pairs.push(`${key}=${encodeURIComponent(params[key])}`);
        }
        var paramStr = pairs.join('&');
        url += paramStr
    }
    return url;
}

/**
 * 构建定长的随机数字字符串
 * @param length 字符串长度
 * @returns {string}
 */
function randomStr(length){
    return _.padStart((Math.random() * Math.pow(10, length)).toFixed(0), length, '0');
}

function buildFlowsetContent(data) {
    if (data.code === 0) {
        var flowset = data.data[0].subAccuInfoList;
        var total = 0;
        var result = '';
        _.each(flowset, function (monthData) {
            var period = moment(monthData.startTime, 'YYYYMMDDhhmmss').format('YYYY年MM月');
            var flowLeft = +monthData.accuAmount;
            total += flowLeft;
            var fr = flowCal(flowLeft);

            result += `${period}结余:${fr.suitable},\n`
        });
        var tr = flowCal(total);
        result += `总计剩余流量:${tr.suitable}`;
        return result;
    } else {
        return data.msg;
    }
}

function flowCal(kb) {
    var mb = (kb / 1024).toFixed(2);
    var gb = (mb / 1024).toFixed(2);

    var result = {
        kb: kb + 'K',
        mb: mb + 'M',
        gb: gb + 'G'
    };
    result.suitable = gb >= 1 ? result.gb : (mb >= 1 ? result.mb : result.kb);
    return result;
}

function coHandler(gen, res){
    co(gen).then(function(result){
        res.json(httpResult.succ(result));
    }).catch(function(err){
        console.log(err);
        res.json(httpResult.err_logic(err));
    });
}
module.exports = {
    flowsetProfile : buildFlowsetContent,
    randomStr : randomStr,
    buildUrl : buildUrlwithParams,
    coHandler : coHandler
};